package application.manager;

import javafx.concurrent.Service;
import lombok.Getter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ServiceManager {

    private static ServiceManager serviceManager = new ServiceManager();

    @Getter
    private Map<Class<? extends Service<?>>, Service<?>> services;

    private ServiceManager() {
        services = new HashMap<>();
    }

    public static ServiceManager getInstance() {
        if (serviceManager == null) {
            serviceManager = new ServiceManager();
        }
        return serviceManager;
    }

    public void register(Class<? extends Service<?>> cls, Service o) {
        this.services.put(cls, o);
    }

    public <T> T lookup(Class<T> cls) {
        return (T) this.services.get(cls);
    }

    public void unregister(Class<?> cls) {
        this.services.remove(cls);
    }

    public void stopAll() {
        Iterator<Map.Entry<Class<? extends Service<?>>, Service<?>>> iterator = services.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Class<? extends Service<?>>, Service<?>> next = iterator.next();
            Service<?> value = next.getValue();
            value.cancel();
            iterator.remove();
        }
    }
}
